package cn.schoolwow.workflow.module.task.action.flow.complete.nodeType.general;

import cn.schoolwow.quickdao.domain.transaction.Transaction;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.workflow.entity.WorkFlowInstance;
import cn.schoolwow.workflow.entity.WorkFlowInstanceCarbonCopy;
import cn.schoolwow.workflow.entity.WorkFlowNode;
import cn.schoolwow.workflow.module.common.flow.AddWorkFlowHistoryFlow;
import cn.schoolwow.workflow.module.task.action.flow.common.AutomaticPassNodeCommonFlow;
import cn.schoolwow.workflow.module.task.action.flow.common.SetNodeAssignerCommonFlow;

import java.util.ArrayList;
import java.util.List;

public class HandleCarbonCopyNodeFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        WorkFlowNode nextNode = flowContext.checkData("nextNode", WorkFlowNode.class);
        WorkFlowInstance workFlowInstance = flowContext.checkInstanceData(WorkFlowInstance.class);
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);

        transaction.addRecordString("插入工作流实例抄送列表信息");

        flowContext.startFlow(new SetNodeAssignerCommonFlow())
                .putCurrentCompositeFlowInstanceData(nextNode)
                .execute();
        List<String> replaceAssignerList = flowContext.checkData("replaceAssignerList", List.class);

        List<WorkFlowInstanceCarbonCopy> workFlowInstanceCarbonCopyList = new ArrayList<>();
        for(String singleAssigner:replaceAssignerList){
            WorkFlowInstanceCarbonCopy workFlowInstanceCarbonCopy = new WorkFlowInstanceCarbonCopy();
            workFlowInstanceCarbonCopy.setInstanceId(workFlowInstance.getId());
            workFlowInstanceCarbonCopy.setCarbonCopy(singleAssigner);
            workFlowInstanceCarbonCopyList.add(workFlowInstanceCarbonCopy);
        }
        transaction.insertIgnore(workFlowInstanceCarbonCopyList);

        flowContext.startFlow(new AddWorkFlowHistoryFlow())
                .putCurrentCompositeFlowData("message", "处理抄送节点["+nextNode.getName()+"]")
                .putCurrentCompositeFlowData("assigner", replaceAssignerList)
                .execute();

        flowContext.startFlow(new AutomaticPassNodeCommonFlow())
                .putCurrentCompositeFlowData("passNode", nextNode)
                .execute();
    }

    @Override
    public String name() {
        return "处理抄送节点流程";
    }
}
